﻿using AccessTeamWorkflow.CommonHelpers;
using AccessTeamWorkflow.EntityHelpers;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AccessTeamWorkflow
{
    public class RemoveUserFromAccessTeam : CodeActivity
    {
        #region Input Parameters
        [RequiredArgument]
        [Input("System User")]
        [ReferenceTarget("systemuser")]
        public InArgument<EntityReference> SystemUser { get; set; }

        [RequiredArgument]
        [Input("Access Team")]
        [ReferenceTarget("teamtemplate")]
        public InArgument<EntityReference> AccessTeam { get; set; }
        #endregion

        #region Output Parameters
        #endregion

        protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                //Create the context and tracing service
                IExecutionContext context = executionContext.GetExtension<IExecutionContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                ITracingService tracer = executionContext.GetExtension<ITracingService>();

                var record = new EntityReference(context.PrimaryEntityName, context.PrimaryEntityId);
                var user = SystemUser.Get(executionContext);
                var accessTeam = AccessTeam.Get(executionContext);
                tracer.Trace("RemoveUserFromAccessTeam:: Calling  AccessTeamHelper");
                var accessTeamHelper = new AccessTeamHelper(service);
                // add the user to access team 
                accessTeamHelper.RemoveUserFromAccessTeam(user.Id, accessTeam.Id, record);
                tracer.Trace("RemoveUserFromAccessTeam:: Exiting workflow");
            }
            catch (Exception ex)
            {
                Helpers.Throw(String.Format("An error occurred in the {0} Custom Workflow Activity.",
                       this.GetType().ToString()),
                     ex);
            }
        }
    }
}
